import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { loadViteEnv } from "vite-electron-plugin/plugin"
import electron from "vite-electron-plugin"
import vueJsx from "@vitejs/plugin-vue-jsx"
import { rmSync } from "fs"

/** 清空 dist */
rmSync("dist", { recursive: true, force: true })

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    electron({
      outDir: "dist",
      include: ["electron"],
      transformOptions: { sourcemap: false },
      plugins: [
        {
          name: "remove-comments",
          transform: ({ code }:{code :any}) => {
            let content = code
            // 匹配 块级注释、行级注释、Region注释
            // \s 是匹配所有空白符, 包括换行; \S 非空白符, 不包括换行
            const pattern1 = /\/\*[\s\S]*?\*\/|(\s)+\/\/[\s\S]*?[\n]+/g
            content = content.replaceAll(pattern1, "\n")
            // 匹配 所有空行
            const pattern2 = /^\s*[\r\n]/gm
            content = content.replaceAll(pattern2, "")
            return content
          }
        },
        loadViteEnv()
      ]
    })
  ],
  css: {
    preprocessorOptions: {
      scss: {
        charset: false,
        additionalData: '@import "@/styles/variables.scss";',
      },
    },
  },
  server: {
    host: "0.0.0.0", //解决 vite use--host to expose
    port: 3000, //配置端口
    // open: true, //配置默认打开浏览器
    // 本地跨域代理
    proxy: {
      "/app": {
        target: "ws://192.168.86.18:3333",
        changeOrigin: true,
      },
      "/ws": {
        target: "ws://localhost:8088",
        changeOrigin: true,
      },
      "/file": {
        target: "http://localhost:8889",
        changeOrigin: true,
      },
      "/v1": {
        target: "http://localhost:8888",
        changeOrigin: true,
      },
      // "/v1": {
      //   target: "http://127.0.0.1:8888",
      //   changeOrigin: true,
      // },
    },
  },
  build: {
    outDir: 'dist', // Vite 构建输出目录
    target: 'esnext', // Electron 使用较高的 ECMAScript 版本
    rollupOptions: {
      external: ['electron'],
      input: 'src/index.html', // 设置入口文件
    },
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});
